<template>
  <!-- 回收管理 -->
  <div>
    <el-table-form ref="form" :model="query">
      <el-form-item label="单据号:" prop="billCode">
        <el-input v-model="query.billCode" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item :table-form-merge="2" class="merge-item" label="回收时间:">
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="回收机构:" prop="orgSNNo">
        <el-tree-select
          v-model="query.orgSNNo"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
        />
      </el-form-item>
      <el-form-item label="单据状态:" prop="billStatus">
        <el-select v-model="query.billStatus" clearable placeholder="请选择">
          <el-option
            v-for="item in orderStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 20px;">
      <div>
        <el-button type="primary" icon="el-icon-circle-plus-outline" @click="openRecallOrderAdd">新增</el-button>
        <el-button type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
        <el-button type="primary" icon="el-icon-printer" @click="print">打印</el-button>
      </div>
    </div>

    <!-- 表单 -->
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:10}"
      class="table"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <recallOrderDetails ref="recallOrderDetails" />
    <recallOrder ref="recallOrder" :payment-method-map="paymentMethodMap" />
  </div>
</template>

<script>
  import { queryExportRecycleList, queryMap, queryRecycleOrderList, recycleOrderDelete } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { parseTime } from '@/utils'
  import { mapGetters } from 'vuex'
  import RecallOrderDetails from './components/RecallOrderDetails'
  import RecallOrder from './components/RecallOrder'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { formatColumnMap } from '@/utils'
  import moment from 'dayjs'

  export default {
    name: 'recoveryManage',
    components: {
      RecallOrderDetails, RecallOrder
    },
    data() {
      return {
        actionColWidth: 80,
        treeData: [],
        paymentMethodMap: [],
        orderStatusMap: [],
        date: [moment().startOf('day'), moment().endOf('day')],
        query: {
          billCode: '',
          orgSNNo: '',
          billStatus: ''
        },
        roleTypeList: [],
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'corpSettingData'
      ]),
      column: function() {
        return [
          {
            prop: 'billCode',
            label: '单据号',
            width: 180,
            render: (h, { row }) => <el-link onClick={() => this.openRecallOrderDetails(row)}>{row.billCode}</el-link>
          },
          {
            prop: 'csmName',
            label: '客户名称',
            width: 110
          },
          {
            prop: 'csmPhone',
            label: '联系方式',
            width: 110
          },
          {
            prop: 'csmAddress',
            label: '地址',
            width: 200
          },
          {
            prop: 'orgName',
            label: '回收机构',
            width: 150
          },
          {
            prop: 'targetUser',
            label: '回收人'
          },
          {
            prop: 'totalAmount',
            label: '费用金额',
            aligh: 'right',
            formatter: function(row) {
              if (!row.reclTotalAmount) {
                row.reclTotalAmount = 0
              }
              if (!row.substituteAmount) {
                row.substituteAmount = 0
              }
              return Number(row.substituteAmount - row.reclTotalAmount).toFixed(2)
            }
          },
          {
            prop: 'happendTime',
            label: '回收时间',
            width: 140,
            render: (h, { row }) => <span>{ row.happendTime && parseTime(row.happendTime, '{y}-{m}-{d} {h}:{i}') }</span>
          },
          {
            prop: 'paymentMethod',
            label: '支付方式',
            render: (h, { row }) => <span>{ row.paymentMethod && formatColumnMap(this.paymentMethodMap, 'value', row.paymentMethod, 'desc') }</span>
          },
          {
            prop: 'remark',
            label: '备注',
            width: 110
          },
          {
            prop: 'billStatus',
            label: '单据状态',
            render: (h, { row }) => <span>{ row.billStatus && formatColumnMap(this.orderStatusMap, 'value', row.billStatus, 'desc') }</span>
          },
          {
            prop: 'auditTime',
            label: '审核时间',
            width: 140,
            render: (h, { row }) => <span>{ row.auditTime && parseTime(row.auditTime, '{y}-{m}-{d} {h}:{i}') }</span>
          },
          {
            prop: 'orderCode',
            label: '关联订单号',
            width: 110
          },
          {
            label: '操作',
            fixed: 'right',
            className: 'action-col',
            width: this.actionColWidth,
            render: (h, { row, $index }) => {
              return (
                <div>
                  {(row.billStatus === 1 || row.billStatus === 3) && <el-link underline={false} size='mini' onClick={() => this.update(row, $index)}>
                    编辑
                  </el-link>}
                  {((this.corpSettingData.sp5 >> 6 & 0x01) === 0) && row.billStatus === 1 && <el-link underline={false} size='mini' onClick={() => this.audit(row, $index)}>
                    审核
                  </el-link>}
                  {((this.corpSettingData.sp5 >> 6 & 0x01) === 0) && row.billStatus === 1 && <el-link underline={false} size='mini' onClick={() => this.del(row, $index)}>
                    作废
                  </el-link>}
                  {((this.corpSettingData.sp5 >> 6 & 0x01) === 0) && row.billStatus === 2 && <el-link underline={false} size='mini' onClick={() => this.audit(row, $index)}>
                    反审核
                  </el-link>}
                </div>
              )
            }
          }
        ]
      }
    },
    async created() {
      await Promise.all([this.queryOptionsMap(), this.getTreeData()])
    },
    methods: {
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.date && this.date.length === 2) {
          query.createTime = moment(this.date[0]).format()
          query.createTimeEnd = moment(this.date[1]).format()
        }
        const diff = moment(this.date[1]).diff(moment(this.date[0]), 'days')
        if (diff > 366) {
          this.$message.warning('回收时间最大支持查询1年')
          return
        }
        const res = await queryRecycleOrderList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2] = await Promise.all([mergeAsyncFunc(queryMap, { enumName: 'RecycleBillStatus' }), mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' })])
        this.orderStatusMap = res1.data // 单据状态
        this.paymentMethodMap = res2.data // 支付方式
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 新增
      async openRecallOrderAdd() {
        await this.$refs.recallOrder.open()
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 编辑
      async update(row) {
        await this.$refs.recallOrder.open(row, 'edit')
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 审核
      async audit(row) {
        await this.$refs.recallOrder.open(row, 'audit')
        this.$refs.lbTable.fetch()
      },
      // 回收单详情
      async openRecallOrderDetails(row) {
        await this.$refs.recallOrder.open(row, 'detail')
      },
      del(row, index) {
        this.$confirm('确认要作废该回收单吗？', '提示', {
          type: 'warning'
        }).then(() => {
          const loading = this.$message({
            message: '正在作废',
            duration: 0,
            iconClass: 'el-icon-loading'
          })
          recycleOrderDelete({ billCode: row.billCode }).then(() => {
            this.tableData.data.splice(index, 1)
            this.$notify({
              title: '提示',
              message: '作废成功',
              type: 'success',
              duration: 2000
            })
          }).finally(() => {
            loading.close()
          })
        })
      },
      // 导出
      exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'info'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          queryExportRecycleList({
            paramInfo: _this._getQuery(_this.query),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      // 打印
      print() {

      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach(it => {
                width += (it.offsetWidth + 10)
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      }
    }
  }
</script>

<style lang='scss' scoped>

</style>
